//
//  BHVersionCheckingObject.m
//  Behing
//
//  Created by Lj on 04/01/2018.
//  Copyright © 2018 lj. All rights reserved.
//

#import "BHVersionCheckingObject.h"

@implementation BHVersionCheckingObject

+ (void)updateVersionChecking:(void(^)(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdata))versionBlock {
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    __block NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];
    NSURLRequest *request;
    NSString *currentBundelId = infoDic[@"CFBundleIdentifier"];
    request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@&country=cn",currentBundelId]]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                versionBlock(currentVersion,@"",@"",NO);
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                if ([appInfoDic[@"resultCount"] integerValue] == 0) {
                    versionBlock(currentVersion,@"",@"",NO);
                    return;
                }
                NSString *appStoreVersion = appInfoDic[@"results"][0][@"version"];
                currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                if (currentVersion.length == 2) {
                    currentVersion  = [currentVersion stringByAppendingString:@"0"];
                }else if (currentVersion.length == 1){
                    currentVersion  = [currentVersion stringByAppendingString:@"00"];
                }
                appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
                if (appStoreVersion.length == 2) {
                    appStoreVersion  = [appStoreVersion stringByAppendingString:@"0"];
                }else if (appStoreVersion.length == 1){
                    appStoreVersion  = [appStoreVersion stringByAppendingString:@"00"];
                }
                if([currentVersion floatValue] < [appStoreVersion floatValue]) {
                    versionBlock(currentVersion,appInfoDic[@"results"][0][@"version"],appInfoDic[@"results"][0][@"trackViewUrl"],YES);
                }else{
                    versionBlock(currentVersion,appInfoDic[@"results"][0][@"version"],appInfoDic[@"results"][0][@"trackViewUrl"],NO);
                }
            });
        }
    }];
    [task resume];
}

@end
